/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.easyedu.dictionary.api.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

/**
 *
 * @author hlavki
 */
public class DbUtils {

    private static final Logger log = Logger.getLogger(DbUtils.class.getName());

    public static void executeSQL(String resource, Connection conn) throws SQLException {
        final Statement stmt = conn.createStatement();
        ClassLoader cl = DbUtils.class.getClassLoader();
        readSQL(new InputStreamReader(cl.getResourceAsStream(resource)), new SQLCallbackHandler() {

            public void doAction(String sql) throws SQLException {
                log.fine("Executing sql command: " + sql);
                stmt.execute(sql);
            }
        });
    }

    private static void readSQL(Reader in, SQLCallbackHandler handler) throws SQLException {
        int ch;
        try {
            StringBuffer sb = new StringBuffer();
            while ((ch = in.read()) != -1) {
                if (ch == ';') {
                    handler.doAction(sb.toString());
                    sb = new StringBuffer();
                } else {
                    sb.append((char) ch);
                }
            }
            String residue = sb.toString();
            if (!"".equals(residue.trim())) {
                handler.doAction(residue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static interface SQLCallbackHandler {

        void doAction(String sql) throws SQLException;
    }
}
